/**************************************************
** GAME VARIABLES
**************************************************/
var canvas,			// Canvas DOM element
	ctx,			// Canvas rendering context
	keys,			// Keyboard input
	localPlayer,	// Local player
	remotePlayers,	// Remote players
	socket;			// Socket connection

var currPlayer;
var currTbl;
var curPos=-1;// vi tri cua minh khi vao choi

/**************************************************
** GAME INITIALISATION
**************************************************/
function init() {
	
	// Initialise socket connection
	socket = io.connect("http://192.168.1.188", {port: 8000, transports: ["websocket", "htmlfile", "xhr-polling", "jsonp-polling"]});
	// Start listening for events
	
	setEventHandlers();
};

/**************************************************
** GAME EVENT HANDLERS
**************************************************/
function sendEventToServer(event,arg){
	socket.emit(event,arg);
};
var setEventHandlers = function() {
	// Socket connection successful
	
	socket.on("connect", onSocketConnected);
	
	socket.on("disconnect", onSocketDisconnect);
	
	// New player message received
	socket.on("login", onNewPlayer);
	
	socket.on("addlevel", addLevelPlayer);
	socket.on("addroom", addRoomPlayer);
	
	//socket.on("sroom",onSelectRoom);
	// New player message received
	
	//socket.on("newTables", addNewTable);

	// Relation make Table
	socket.on("ctable",onCreateTable);
	//socket.on("STable",onSelectTable);

	// Player move message received
	//socket.on("move player", onMovePlayer);

	// Player removed message received
	//socket.on("remove player", onRemovePlayer);
};

// Socket connected
function onSocketConnected() {
	//addMessage("</br>Connected to socket server");
	//
	$('#toolbar').css('background', '#65A33F');
    $('#socketStatus').html('Connected to server');
	// Send local player data to the game server
    
    var obj = getInfoUser();
    
    socket.emit("login", {session_id:obj[0],sign_user:obj[1],username:obj[2]});
};

// Socket disconnected
function onSocketDisconnect() {
	//alert('');
	console.log("Disconnected from socket server");
};

// New player
function onNewPlayer(data) {
	//addMessage(data.username+":"+data.markunit);
	var username = data.username;
	var markunit = data.markunit;
	var txt = document.createTextNode(username);
	document.getElementById("namePlayer").appendChild(txt);
	txt = document.createTextNode(markunit);
	document.getElementById("agPlayer").appendChild(txt);
	currPlayer = new objPlayer(username,markunit,'192.168.1.123');
	addMessage(JSON.stringify(data));
};

//Alter Login Add Level
function addLevelPlayer(data){
	addMessage(""+JSON.stringify(data));
	var ul = document.createElement('ul');
	document.getElementById("btnLvl").appendChild(ul);
	for(var i=0;i<data.length;i++){
		var li= document.createElement('li');
		li.setAttribute('onclick','selectLevel('+data[i].Id+')');
		li.setAttribute('class','btnJoinLvl');
		var str = data[i].Name;
		var span = document.createElement('span');
		span.setAttribute('class','line1');
		var txt = document.createTextNode(str);
		span.appendChild(txt);
		li.appendChild(span);
		var br= document.createElement('br');
		li.appendChild(br);
		span = document.createElement('span');
		span.setAttribute('class','line2');
		if(i==0){
			span.appendChild(document.createTextNode('Vào cửa tự do'));
		}else span.appendChild(document.createTextNode('Trên 5000 AG'));		
		li.appendChild(span);
		ul.appendChild(li);
	}
};

function selectLevel(id){
	document.getElementById("wrapperLV").style.display="none";
	document.getElementById("wrapperSG").style.display="block";
	document.getElementById("wrapperPG").style.display="none";
	sendEventToServer('slevel',id);
}

//Add Room
function addRoomPlayer(data){
	addMessage(""+JSON.stringify(data));
	for(var i=0;i<data.length;i++){
		var a = document.createElement('a');
		if(i==0) a.setAttribute('class','actDep');
		a.setAttribute('onclick','selectRoom('+data[i].Id+')');
		var str = data[i].Name+" ("+data[i].CurPlay+"/"+data[i].MaxPlay+")";
		var txt = document.createTextNode(str);
		a.appendChild(txt);
		document.getElementById("selectDep").appendChild(a);
	}
	var userName = currPlayer.name;
	var userAG = currPlayer.mark;
	document.getElementById("nameInfo").appendChild(document.createTextNode(userName));
	document.getElementById("moneyInfo").appendChild(document.createTextNode(userAG));
};

function selectRoom(iden){
	var m = document.getElementById('selectDep').getElementsByTagName('a');
	var count;
	if(m[iden-1].className=='actDep') return;
	else{
		for(var i=0;i<m.length;i++){
			if(m[i].className=='actDep'){
				count = i;
				m[i].className='';
				break;
			}
		}
		m[iden-1].className = 'actDep';
		iden++;
		count++;
		document.getElementById('gameDep'+count).style.display = 'none';
		document.getElementById('gameDep'+iden-1).style.display = 'block';
	}
	sendEventToServer('sroom',{id:iden});
}

//Create Table
function clickCreateTbl(){
	displayPopup(1);
}
function createTbl(){
//	var arr = JSON.parse(data);
//	addMessage("</br>"+data);	
	var radioValue=null;
	for (var i=0;i<document.getElementsByName('createTbl').length;i++) {
		if (document.getElementsByName('createTbl')[i].checked) {
			radioValue = document.getElementsByName('createTbl')[i].value;
			break;
		}
	}
	var nameTbl = document.getElementById('tblName').value;
	sendEventToServer('ctable',{Name:nameTbl,Mark:radioValue});
};
function initTbl(data){
	currTbl = new objTable(data.Id,data.Name,data.MarkUnit);
	currTbl.addPlayer(currPlayer);
	currPlayer.isCreateTbl = true;
	loadDataBT(true,false,currPlayer.name,currPlayer.mark,currPlayer.ip);
	var str = objTable.id +" -- "+ objTable.markUnit;
	document.getElementById("infoTbl").appendChild(document.createTextNode(str));
}


function joinTbl(data){
	document.getElementById("wrapperLV").style.display="none";
	document.getElementById("wrapperSG").style.display="none";
	document.getElementById("wrapperPG").style.display="block";
	
	currTbl = new objTable(data.Id,data.Name,data.MarkUnit);
	currTbl.addPlayer(currPlayer);
	var str = objTable.id +" -- "+ objTable.markUnit;
	document.getElementById("infoTbl").appendChild(document.createTextNode(str));
	loadDataBT(true,false,currPlayer);
	if(currTbl.numPlayer==2){
		loadDataBT(false,false,currTbl.arrPlayer[0]);
	}else if(currTbl.numPlayer==3){
		loadDataRL(true,false,currTbl.arrPlayer[0]);
		loadDataBT(false,false,currTbl.arrPlayer[1]);
	}else if(currTbl.numPlayer==4){
		loadDataRL(true,false,currTbl.arrPlayer[0]);
		loadDataBT(false,false,currTbl.arrPlayer[1]);
		loadDataRL(false,false,currTbl.arrPlayer[2]);
	}
	currPos=currTbl.numPlayer-1;
}

function otherJoinTbl(data){
	var tempPlayer = new objPlayer(data.Name,data.Mark,/*data.ip*/'123.456.789.1');
	currTbl.addPlayer(tempPlayer);
	if(currTbl.numPlayer==2){
		loadDataBT(false,false,currTbl.arrPlayer[1]);
	}else if(currTbl.numPlayer==3){
		if(curPos==0){
			loadDataRL(true,false,currTbl.arrPlayer[1]);
			loadDataBT(false,false,currTbl.arrPlayer[2]);
		}else if(curPos==1){
			loadDataRL(false,false,currTbl.arrPlayer[0]);
			loadDataBT(false,false,currTbl.arrPlayer[2]);
		}
	}else if(currTbl.numPlayer==4){
		if(curPos==0){
			loadDataRL(true,false,currTbl.arrPlayer[1]);
			loadDataBT(false,false,currTbl.arrPlayer[2]);
			loadDataRL(false,false,currTbl.arrPlayer[3]);
		}else if(curPos==1){
			loadDataRL(false,false,currTbl.arrPlayer[0]);
			loadDataRL(true,false,currTbl.arrPlayer[2]);
			loadDataBT(false,false,currTbl.arrPlayer[3]);
		}else if(curPos==2){
			loadDataBT(false,false,currTbl.arrPlayer[0]);
			loadDataRL(false,false,currTbl.arrPlayer[1]);
			loadDataRL(true,false,currTbl.arrPlayer[3]);
		}		
	}
}

function leaveTbl(data){
	var index=-1;
	for(var i=0;i<currTbl.numPlayer;i++){
		if(currTbl.arrPlayer[i].name == data.Name){
			index=i;break;
		}
	}
	currTbl.removePlayer(index);
	if(index==curPos){
		document.getElementById("wrapperLV").style.display="none";
		document.getElementById("wrapperPG").style.display="none";
		document.getElementById("wrapperSG").style.display="block";
	}else if(index==0){
		document.getElementById("wrapperLV").style.display="none";
		document.getElementById("wrapperPG").style.display="none";
		document.getElementById("wrapperSG").style.display="block";
		alert("Chủ bàn hủy ván");
	}else{
		if(document.getElementById("infoSeatTop")!=null) removeElement('tblGame','infoSeatTop');
		if(document.getElementById("infoSeatLeft")!=null) removeElement('tblGame','infoSeatLeft');
		if(document.getElementById("infoSeatRight")!=null) removeElement('tblGame','infoSeatRight');
		if(index<curPos) curPos--;
		if(curPos==0){// chu ban
			if(currTbl.numPlayer==2){
				loadDataBT(false,false,currTbl.arrPlayer[1]);
			}else if(currTbl.numPlayer==3){
				loadDataRL(true,false,currTbl.arrPlayer[1]);
				loadDataBT(false,false,currTbl.arrPlayer[2]);
			}
		}else if(curPos==1){//vi tri thu 2 trong 2 hoac 3 thag
			if(currTbl.numPlayer==2){
				loadDataBT(false,false,currTbl.arrPlayer[0]);
			}else if(currTbl.numPlayer==3){
				loadDataRL(false,false,currTbl.arrPlayer[0]);
				loadDataBT(false,false,currTbl.arrPlayer[2]);	
			}
		}else if(curPos==2){//vi tri thu 3 trong 3 thag
			loadDataRL(false,false,currTbl.arrPlayer[0]);
			loadDataBT(false,false,currTbl.arrPlayer[1]);
		}
	}
}

// Tim kiem ban choi
function clickFindTable(){
	displayPopup(2);
}
// Join vao ban da tim
function joinFindTbl(){
	var idTbl = document.getElementById('tblId').value;
//	sendEventToServer('jtable',{id:idTbl});
//	joinTbl(data);
}



//Add new a table
function addNewTable(data){
	var arr = JSON.parse(data);
	addMessage("</br>"+data);
};

// Move player
function onMovePlayer(data) {
	var movePlayer = playerById(data.id);
	// Player not found
	if (!movePlayer) {
		console.log("Player not found: "+data.id);
		return;
	};
	// Update player position
	movePlayer.setX(data.x);
	movePlayer.setY(data.y);
};
function addMessage(data){
	$('#socketStatus').html('Data:'+data);
}
